<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>documentName</title>
  </head>

  <body>
    <canvas id="myCanvas" width="600" height="300">
      <p>您的浏览器不支持 canvas!</p>
    </canvas>

    <div id="brandImgDiv"></div>

    <button onclick="downLoad()">下载</button>

    <script src="/node_modules/jquery/dist/jquery.min.js"></script>
    <!-- <script src="/node_modules/jcanvas/dist/jcanvas.js"></script> -->
    <script src="/node_modules/jcanvas/dist/jcanvas.js"></script>
    <script>
      var $myCanvas = $('#myCanvas')

      var imgUrl = ''

      $myCanvas.drawText({
        // 需要绘制的文本内容
        text: 'Canvas 绘制文字 Api',

        // 设置文本的字体
        fontFamily: 'cursive', // 'Verdana'; 'sans-serif'

        /**
         * @brief: 设置文本大小
         * @param: {Number | String} fontSize
         * 纯数字：jCanvas将其解释为以像素为单位的值；(fontSize: 40 --- fontSize: '40px')
         * 带单位的字符串：fontSize: '30pt'
         * @tip: {*} >3个点时才有效
         * */
        fontSize: 40,

        // 文本绘制的起始位置
        x: 290,
        y: 150,
        fillStyle: 'lightblue',
        strokeStyle: 'blue',
        strokeWidth: 1,
      })

      var image = new Image()
      // image.src = $('#myCanvas').getCanvasImage('jpeg')
      bas364 = $('#myCanvas')[0].toDataURL('image/jpg') // 调 canvas 实例的方法
      image.src = bas364
      imgUrl = bas364
      image.width = 158
      image.height = 158
      $('#brandImgDiv').empty()
      $('#brandImgDiv').append(image)

      console.log(imgUrl)

      /**
       * @brief: 前端下载 base 64 文件
       * @return {*}
       */
      function downLoad() {
        // 如果浏览器支持 msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
        if (window.navigator.msSaveOrOpenBlob) {
          var bstr = atob(imgUrl.split(',')[1])
          var n = bstr.length
          var u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          var blob = new Blob([u8arr])
          window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
        } else {
          // 这里就按照chrome等新版浏览器来处理
          const a = document.createElement('a')
          a.href = imgUrl
          a.setAttribute('download', 'chart-download')
          a.click()
        }
      }

      // 这里是获取到的图片base64编码,这里只是个例子哈，要自行编码图片替换这里才能测试看到效果
    </script>
  </body>
</html>
